"""工具函数模块"""
import os
import platform
import subprocess
from typing import Optional

API_KEY_ENV_NAME = "YT_API_KEY"


def load_shell_environment() -> None:
    """自动加载shell配置文件，解决环境变量立即生效问题"""
    if platform.system() not in ("Linux", "Darwin"):
        return

    config_files = [
        os.path.expanduser("~/.bashrc"),
        os.path.expanduser("~/.zshrc"),
        os.path.expanduser("~/.bash_profile"),
        os.path.expanduser("~/.profile")
    ]

    for config_file in config_files:
        if not os.path.exists(config_file):
            continue

        try:
            result = subprocess.run(
                args=f"/bin/bash -c 'source {config_file} && echo ${API_KEY_ENV_NAME}'",
                shell=True,
                capture_output=True,
                text=True
            )

            loaded_api_key = result.stdout.strip()
            if loaded_api_key and loaded_api_key != "$" + API_KEY_ENV_NAME:
                os.environ[API_KEY_ENV_NAME] = loaded_api_key
                break

        except Exception:
            continue


def get_api_key_from_env() -> Optional[str]:
    """从环境变量获取API密钥"""
    load_shell_environment()
    api_key = os.getenv(API_KEY_ENV_NAME)
    return api_key.strip() if api_key and api_key.strip() else None


def check_file_overwrite(file_path: str) -> bool:
    """检查文件是否存在并询问是否覆盖"""
    if not os.path.exists(file_path):
        return True

    while True:
        user_choice = input(f"文件 [{file_path}] 已存在，是否覆盖？(y/n): ").strip().lower()
        if user_choice in ("y", "yes"):
            return True
        elif user_choice in ("n", "no"):
            return False
        else:
            print("警告：请输入 y 或 n")
    